import loadImages from "./loadImages";
import loadVideos from "./loadVideos";

export default function (obj, onprogress) {
    var opt = Object.assign({
        images: [], // 待加载的图片 [src|[src,weight]]
        videos: [], // 待加载的视频 [src|[src,weight]]
        promises: [], // 待兑现的promise [promise|[promise,weight]]
    }, obj);
    var totalWeight = opt.images.concat(opt.videos, opt.promises).reduce(function (pre, cur) {
        if (Array.isArray(cur)) {
            pre += cur[1];
        } else {
            pre += 1;
        }
        return pre;
    }, 0);
    var finishedWeight = 0;
    var onEach = onprogress && function (weight) {
        finishedWeight += weight;
        var progress = Math.floor(finishedWeight * 100 / totalWeight);
        onprogress(progress);
    };

    return new Promise(function (resolve, reject) {
        Promise.all([
            loadImages(opt.images, onEach),
            loadVideos(opt.videos, onEach),
            Promise.all(opt.promises.map(function (param) {
                if (Array.isArray(param)) {
                    var p = param[0];
                    var weight = param[1];
                } else {
                    var p = param;
                    var weight = 1;
                }
                return new Promise(function (resolve, reject) {
                    p.then(function (d) {
                        onEach && onEach(weight);
                        resolve(d);
                    }).catch(function (e) {
                        onEach && onEach(weight);
                        reject(e);
                    });
                });
            })),
        ]).then(function (arr) {
            resolve({
                images: arr[0],
                videos: arr[1],
                promises: arr[2],
            });
        }).catch(reject);
    });
}
